import React, {Component} from 'react'
import styles from './detail.less'
import { Button, message } from 'antd'
import TabsControl from "../components/tabs"
import Img from "@/components/Img/Img";
import { withRouter } from 'dva/router'
import { connect } from 'dva'
import isEmpty from 'lodash/isEmpty'
import { GET_BOOK_DETAIL } from "../../../actions/book"

@connect(({ book }) => ({
  book
}))
class Detail extends Component {
  toConfirmPage(id) {
    this.props.history.push(`/book/order/${id}`)
  }

  componentDidMount() {
    const {dispatch, match: {params: {id}}} = this.props
    dispatch(GET_BOOK_DETAIL(id))
  }

  addShoppingCar(detail) {
    let shoppingCar = localStorage.getItem('shoppingCar')
    const {id, cover, price, packaging, status, title} = detail
    if (shoppingCar) {
      let newCar = JSON.parse(shoppingCar)
      newCar.push({id, cover, price, packaging, status, title})
      localStorage.setItem('shoppingCar', JSON.stringify(newCar))
    } else {
      localStorage.setItem('shoppingCar', JSON.stringify([{id, cover, price, packaging, status, title}]))
    }
    message.destroy()
    message.success('操作成功')
  }

  render() {
    const {book: { detail }} = this.props
    const { author, title, tags, cover, buyers, price, detail: bookDetail, id } = detail
    return (
      !isEmpty(detail) && <div className={styles.detailContainer}>
        <div className={styles.detailContentBox}>
          <div className={styles.detailContent}>
            <div className={styles.detailImg}>
              <Img src={cover}/>
            </div>
            <div className={styles.detailInfo}>
              <h2 className={styles.detailTitle}>{title}</h2>
              {
                tags && tags.split(',').map(item => {
                  return (
                    <span className={styles.classHour}>
                      <span className={styles.classHourText}>{item}</span>
                    </span>
                  )
                })
              }
              <h3 className={styles.detailTeacher}>作者：{author}</h3>
              <div className={styles.detailBuy}>
                已购买：{buyers}人
              </div>
              <div className={styles.detailCount}>
                ¥ {(price / 100).toFixed(2)}
              </div>
              <div style={{overflow: 'hidden'}}>
                <Button className={styles.buttonBuy} onClick={this.toConfirmPage.bind(this, id)}>立即购买</Button>
                <Button className={styles.buttonShoppingCar} onClick={this.addShoppingCar.bind(this, detail)}>加入购物车</Button>
              </div>
            </div>
          </div>
        </div>
        <div style={{paddingBottom: 192}}>
          <TabsControl bookDetail={bookDetail}/>
        </div>
      </div>
    );
  }
}

export default withRouter(Detail);